from django.shortcuts import render

# Create your views here.
# -*- coding: utf-8 -*-

from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from ops.hades.models import Instance, Query
from ops.hades.utils.sql import Engines
from ops.hades.serializers.querySerializers import QueryModelSerializer
import time

class QuerySerializer(QueryModelSerializer):
    """
    字典-序列化器
    """
    class Meta:
        model = Query
        fields = '__all__'
        # exclude = ['passwd']
        read_only_fields = ["id"]


class QueryViewSet(ModelViewSet):
    """
    字典管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    exclude_field = ['passwd']
    queryset = Query.objects.all()
    values_queryset = None
    serializer_class = QuerySerializer
    extra_filter_backends = []
    permission_classes = []
    search_fields = ["devices_name", "devices_num", "devices_type", "remark", "devices_localip", "devices_interip"]

    def get_queryset(self):
        if getattr(self, 'values_queryset', None):
            return self.values_queryset
        return super().get_queryset()

    def create(self, request, *args, **kwargs):
        # 获取post提交的body数据
        data = request.data

        # 获取用户名
        data['username'] = request.user.username

        # 根据instance_id获取name，存入数据库
        instance = Instance.objects.get(id=data.get('instance_id')).name
        data['instance'] = instance
        data['time_query'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        if data:
            db_type = data.get('db_type')
            print(db_type)
            engine = Engines.get_engine(db_type)
            res = engine.exec(**data)
            Query.username = '未定义'
            return Response(res)
        msg = '数据为空，请检查'
        return Response(msg, status=status.HTTP_400_BAD_REQUEST)
    # Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        data = request.GET
        if data:
            db_type = data.get('db_type')
            engine = Engines.get_engine(db_type)
            res = engine.exec(**data)
            Query.username = '未定义'
            return Response(res)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

